<!DOCTYPE html>
<html>
  
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  <meta name="author" content="Amos Zhu">
  
  
  <title>缓存与数据库双写一致性的解决方案——附上代码解决方案 | Amos的技术博客</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="stuff,redis,stuff,Spring Boot,">
  

  
  <meta name="description" content="传统企业中为了解决高并发大流量的问题，通常使用缓存+数据库的方式来支撑高QPS的访问，虽然能解决读QPS的问题，但是同时也引入了新的问题，例如：缓存与数据库的数据不一致的情况；本博文参考网上相关的博文，详细的整理下缓存数据库数据一致性的问题，并且给出基于Java的代码解决方案">

  

  
    <script src="//cdn.jsdelivr.net/npm/leancloud-storage@3.11.1/dist/av-min.js" async></script>
  

  
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML" async></script>
  

  
    <script src="//unpkg.com/valine/dist/Valine.min.js" async></script>
  

  

  <script>
  // theme-ad's config script
  // it can be used in every script
  
  window.AD_CONFIG = {
    leancloud: {"appid":"eObxCkTJ6j4GzRxGLgiHyfJa-gzGzoHsz","appkey":"fzRMAFC6MCE11mp7mnvh4Kwe","comment":true,"count":true},
    welcome: {"enable":true,"interval":30},
    start_time: "2019-05-28",
    passwords: ["efe07af7441da2b69c4a41e42e73be4db47f66010a56900788a458354a7373ec", ],
    is_post: true,
    lock: false,
    author: "Amos Zhu",
    share: {"qq":true,"wechat":true},
    mathjax: true,
    page_type: "",
    root: "/blog/"
  };
</script>

  <script src="/blog/vendor/sha256.min.js"></script>
<script src="/blog/js/auth.js"></script>
<script src="/blog/js/index.js"></script>
<script src="/blog/vendor/qrcode.min.js"></script>

  
    <link rel="icon" href="/blog/images/favicon.ico">
    <link rel="apple-touch-icon" href="/blog/images/touch-icon.png">
  

  <link href="//netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <link rel="stylesheet" href="/blog/css/index.css">
<link rel="stylesheet" href="/blog/styles/components/highlight/highlight.css">

  
</head>
  <body>
    <header class="site-header">
  <div class="site-header-brand">
    
      <span class="site-header-brand-title">
        <a href="/blog/">Amos Zhu</a>
      </span>
    
    
      <span class="site-header-brand-motto"> | 当浮躁的心静不下，不妨写些东西或者看会书</span>
    
  </div>
  <div class="site-header-right">
    <nav class="site-header-navigation">
      
        <a href="/blog/" target="_self">首页</a>
      
        <a href="/blog/archives/" target="_self">归档</a>
      
        <a href="/blog/tags/" target="_self">标签</a>
      
        <a href="/blog/categories/" target="_self">分类</a>
      
        <a href="/blog/redis/" target="_self">redis</a>
      
        <a href="/blog/rabbitMQ/" target="_self">rabbitMQ</a>
      
        <a href="/blog/elasticsearch" target="_self">elasticsearch</a>
      
        <a href="/blog/stuff" target="_self">stuff</a>
      
        <a href="/blog/kafka" target="_self">kafka</a>
      
        <a href="/blog/friends/" target="_self">友链</a>
      
        <a href="/blog/about/" target="_self">关于</a>
      
    </nav>
    <div class="site-header-btn">
      
        <a href="https://gitee.com/amos_zhu" target="_blank" id="site-github">
          <i class="fa fa-github-alt"></i>
        </a>
      
      <a href="javascript:void(0);" id="site-search">
        <i class="fa fa-search"></i>
      </a>
      <a href="javascript:void(0);" id="site-nav-btn">
        <i class="fa fa-ellipsis-v"></i>
      </a>
    </div>
  </div>
</header>
<nav class="table-content" id="site-nav">
  <div class="table-content-title">
    <span>导航</span>
  </div>
  <div class="table-content-main">
    <ol class="toc">
      
        <li class="toc-item">
          <a href="/blog/" target="_self">
            首页
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/archives/" target="_self">
            归档
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/tags/" target="_self">
            标签
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/categories/" target="_self">
            分类
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/redis/" target="_self">
            redis
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/rabbitMQ/" target="_self">
            rabbitMQ
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/elasticsearch" target="_self">
            elasticsearch
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/stuff" target="_self">
            stuff
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/kafka" target="_self">
            kafka
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/friends/" target="_self">
            友链
          </a>
        </li>
      
        <li class="toc-item">
          <a href="/blog/about/" target="_self">
            关于
          </a>
        </li>
      
    </ol>
  </div>
</nav>
<div id="site-process"></div>
    <main>
      
  <div class="passage">
  <div class="passage-meta">
    <span>
      <i class="fa fa-calendar"></i>2019-08-19
    </span>
    
      <span>
        | <a href="/blog/categories/stuff/"><i class="fa fa-bookmark"></i>stuff</a>
      </span>
    
    
      <span>
        | <i class="fa fa-unlock-alt"></i>UNLOCK
      </span>
    
  </div>
  <h1 class="passage-title">
    缓存与数据库双写一致性的解决方案——附上代码解决方案
  </h1>
  
  <article class="passage-article">
    <p><strong>本文参考中华石杉的教程，感谢大神的分享</strong><br>关于缓存数据库数据一致性的解决方案，网上有很多，但是大都是偏向理论的，且大多数使用分布式锁来实现的，分布式锁也是一种解决方式，但是无疑增加了代码逻辑的复杂性，本博文主要是使用JVM自带的缓存队列+线程池来解决数据一致性的问题，并且针对数据一致性的解决方案通过代码来体现出来，让读者能不仅对数据一致性的原因以及解决方案有更深层次的理解，并且也能落实到代码上</p>
<h3 id="谈谈缓存与数据库数据一致性的问题"><a href="#谈谈缓存与数据库数据一致性的问题" class="headerlink" title="谈谈缓存与数据库数据一致性的问题"></a>谈谈缓存与数据库数据一致性的问题</h3><p>系统中引入了缓存，这里我们使用Redis,我们会先将数据缓存在Redis中，当外部请求数据时，我们都是先从Redis中查询，如果查询到了直接返回给请求，如果查询不到，则再到数据中进行查询，返回给请求，同时再将数据写入到Redis中。具体的业务逻辑如下图：</p>
<p><img src="https://s2.ax1x.com/2019/08/15/mEMuw9.png" alt="image"></p>
<ul>
<li>用户发起请求</li>
<li>系统先从缓存中查询是否有相关的数据，如果存在则直接返回给用户</li>
<li>如果缓存中不存在，则到数据库中查询，查询到的结果再返回给用户，同时写入到缓存中</li>
</ul>
<p><strong>优点</strong>：</p>
<p>这样做的好处是，如果缓存中有数据了，就直接返回，减少了数据库的访问压力，同时也提高了请求响应的数据（少了与数据库之间的交互）</p>
<p><strong>缺点</strong>:</p>
<p>虽然读数据的性能提升了，但是给数据更新造成了新的麻烦，在高并发的场景中很容易就造成了缓存与数据库数据一致性的问题</p>
<p>一般情况下，我们写数据有两种方式：</p>
<ul>
<li>先更新缓存，再更新数据库</li>
</ul>
<p>针对这种方案，我们来分析下：</p>
<ol>
<li>先写缓存，如果写入缓存失败，直接返回，无影响</li>
<li>写入缓存之后，再来写数据库，测试数据库写入失败，如果不清除缓存中的数据，就会造成缓存与数据库中的数据不一致</li>
<li>如果增加清除缓存中的数据，那么清除数据失败怎么处理</li>
</ol>
<ul>
<li>先更新数据库，再更新缓存</li>
</ul>
<p>我们再来分析这种方案：</p>
<ol>
<li>先更新数据库，如果更新数据库失败，直接返回，无影响</li>
<li>写入数据库成功之后 ，再来更新缓存中的数据，如果更新失败，则此时缓存中的数据与数据库中的数据就会不一致，需要添加重试机制，增加代码量，并且业务逻辑复杂化，</li>
<li>就算增加了重试机制，如果重试也失败了，该如何处理</li>
</ol>
<p>以上的两种方案都是有缺陷的，那么我们该如何处理呢，我们一步步来分析：</p>
<p>以上两种方案都是如果一方的更新失败了，都会造成数据不一致的情况，那么需要想办法来处理，就算一方失败了，也不会出现数据不一致的情况。</p>
<p>怎么处理呢？这里我们先这样处理：</p>
<ul>
<li>先删除缓存中的数据，然后再去更新数据库，最后更新缓存中的数据</li>
</ul>
<ol>
<li>写请求过来，我们先删除缓存中的数据，</li>
<li>删除成功之后，我们再更新数据库中的数据，此时如果更新数据库中的数据失败，则整个写请求失败，直接返回，数据没有发生变化，此时读请求过来，发现缓存中没有对应的数据，则会从数据库中读取数据，同时将数据写入到缓存中，此时缓存中的数据和数据库中的数据都是一样的， 不存在数据一致性的问题</li>
<li>更新数据库中的数据之后 ，再来更新缓存中的数据，此时更新缓存中的数据失败，直接返回，数据库中的数据是最新的数据，开始读请求过来，发现缓存中没有对应的数据，则会从数据库中读取数据，同时将数据写入到缓存中，此时缓存中的数据和数据库中的数据都是一样的， 不存在数据一致性的问题</li>
<li>更新缓存成功，此时缓存中的数据和数据库的数据是一致的，不存在数据一致性的问题</li>
</ol>
<p>具体的业务逻辑见下图：<br><img src="https://s2.ax1x.com/2019/08/19/m3siM4.png" alt="image"></p>
<p>乍一看，这种方案完美的解决了数据一致性的问题，我们不妨再来将业务场景复杂点，并发量再大一点，比如说每秒的读QPS为1w+，这是我们再来分析下上述方案的业务逻辑：</p>
<ol>
<li>用户写请求过来，我们还是先删除缓存，然后再更新数据库</li>
<li>在更新数据库的过程中，此时更新还没有完成，数据库的值依旧是原来的旧值，这时一个读请求过来</li>
<li>发现缓存中没有值，就会到数据库中去查询数据，然后写入到缓存中，此时数据库还没有更新结束，读请求获取的数据依旧是原来的旧数据</li>
<li>这时数据库更新完成，但是更新缓存失败，此时缓存中是用的之前的旧数据与数据库中的新数据就会出现数据不一致的情况，数据一致性的问题又出现了</li>
</ol>
<p>具体的业务逻辑如下图：</p>
<ul>
<li style="list-style: none"><input type="checkbox"> 业务流程图</li>
</ul>
<p>由此可见，上述的方案也是存在问题的，尤其是并发量很大的情况下，这类现象出现的几率就很大；对于这种情况我们该如何处理呢？</p>
<p><strong>分析</strong>：</p>
<p>我们仔细分析上述的情况，可以发现，读请求和写请求是并行的，这是导致数据一致性的根本原因，并行的请求会导致数据一致性的问题，那么解决此类问题的思路就有了——<strong>将请求串行</strong>！</p>
<p>具体的业务逻辑如下：</p>
<ol>
<li>写请求过来，将写请求缓存到缓存队列中，并且开始执行写请求的具体操作（删除缓存中的数据，更新数据库，更新缓存）</li>
<li>如果在更新数据库过程中，又来了个读请求，将读请求再次存入到缓存队列中，等待队列前的写请求执行完成，才会执行读请求</li>
<li>之前的写请求删除缓存失败，直接返回，此时数据库中的数据是旧值，并且与缓存中的数据是一致的，不会出现缓存一致性的问题</li>
<li>写请求删除缓存成功，则更新数据库，如果更新数据库失败，则直接返回，写请求结束，此时数据库中的值依旧是旧值，读请求过来后，发现缓存中没有数据， 则会直接向数据库中请求，同时将数据写入到缓存中，此时也不会出现数据一致性的问题</li>
<li>更新数据成功之后，再更新缓存，如果此时更新缓存失败，则缓存中没有数据，数据库中是新值 ，写请求结束，此时读请求还是一样，发现缓存中没有数据，同样会从数据库中读取数据，并且存入到缓存中，其实这里不管更新缓存成功还是失败， 都不会出现数据一致性的问题</li>
</ol>
<p>具体的业务逻辑如下图：<br><img src="https://s2.ax1x.com/2019/08/19/m3yHBj.png" alt="image"></p>
<p>上述的解决方案是将异步请求串行化，这样做的好处呢就是队列上的工作线程完成之后上一个操作数据库的修改之后，才会执行下一个操作。</p>
<p>上述的解决方案中还有个可以优化的地方，如果在修改数据库更新缓存的过程中，不断有读请求过来怎么处理，队列中都一次防止每次的读请求么，不是的，存放大多的队列只会占用队列的资源，我们这里可以判断过滤下读请求，直接返回，提示用户刷新下页面，重新请求数据，这个过程足够队列中写操作执行完成了，读请求再次请求过来时，可以直接返回缓存即可</p>
<h3 id="注意点"><a href="#注意点" class="headerlink" title="注意点"></a>注意点</h3><ol>
<li>读请求长时间阻塞</li>
</ol>
<p>方案中对读请求做了异步化，当从缓存中读取不到数据，则将该读请求写入缓存队列中，此时一定要注意读请求超时的问题，系统设计要做到每个读请求都在必须要在超时时间内完返回请求结果。</p>
<p>在该方案中，如果大量的写请求进入，存放到缓存队列中，这样后来的读请求就会发现在缓存中读取不到数据，也进入到缓存队列中，我们这里来做个简单的假设，如果一个写请求需要50ms的时间，当队列中存在4个写请求的话,就会由200ms的读请求延迟，一般读请求200ms的延迟，用户是可以接受的。</p>
<p>一次类推，如果一下子来了500个写请求，在单机的基础上，则需要25000ms，这个时间相当长了，所以这时我们需要分布式来解决这个问题，将访问的压力分打给其他的服务实例，比如一个单机，20个队列，每个队列中的写操作需要耗时50ms，则大概需要25个单机就可以hold住每秒500个写请求了，当然这个缓存队列的配置还需要跟服务器的内存和实际压测过程中的情况去调节缓存队列中的核心线程数和最大线程数。</p>
<p>当然上面只是一个大概数据的估算，在实际生产环境中一般呈现二八定律的，按照个比率来估算每秒的写请求也是可以的</p>
<p>总结下：当写请求大量的请求过来的时候，如果此时又有大量的读请求的话，单机版本的可能会造成读请求时间过长，我们这里是通过分布式服务的方式来分担写请求的访问压力，通过分担的方式加快写请求的操作，这样读请求返回的时间就快了</p>
<ol start="2">
<li>读请求并发量较高</li>
</ol>
<p>还有一个场景就是大量的读请求过来，这个场景和上述的场景比较像，比如说每秒有500个写请求过来，按照上述的方案，会先删除缓存，此时关于这个缓存会有大量的读请求过来，我们按照读写比例20:1的比率来算，就是一个写请求对应20个读请求，那么500个写请求就会由1w个读请求，此时如果还是使用单机的话，1w个读请求（都是缓存被删除的）,此时单机版本肯定是玩不转的了，我们还是需要水平横向扩展，通过增加服务处理的实例，来分担QPS的压力，但是对于缓存执行更新的操作，还是需要通过Nginx服务器来路由到相同的服务实例上</p>
<ol start="4">
<li>热点数据的路由问题，导致请求倾斜</li>
</ol>
<p>准确来说这个场景和秒杀比较像，但是场景比较像但是解决的方案则是不一样的，秒杀有秒杀自己的一套解决方案，这里主要是热点数据的QPS非常高，我们前面通过Nginx服务器会将对于该热点数据的请求全部路由到相同的服务实例上，就会造成该服务实例的压力会很大，这个时候需要根据情况来处理</p>
<p>以上就是我们本次缓存数据库双写一致性的解决方案，该方案能解决一部分的问题，但是在实际的生产场景中，还是需要考虑该方案一些注意的要点，结合自己的业务场景来调整该方案，通过模拟、极限压测等方式来优化，落地一套相对比较完善的数据一致性的解决方案</p>
<h3 id="代码实现"><a href="#代码实现" class="headerlink" title="代码实现"></a>代码实现</h3><p>以上我们详细的分析了数据一致性的解决方案的原理和需要注意的地方，下面我们来通过Java代码来实现该方案</p>
<p>上面的方案中我们已经讨论过，通过JVM待在的缓存队列来缓存读写的请求，并且将所有的请求异步串行化，这里我们使用SpringBoot框架来进行代码实现</p>
<ol>
<li>首先我们先在系统启动的时候，初始化线程池和缓存队列</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span> com.amos.common.config</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span> ServletListenerRegistrationConfig</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span> 在容器启动的时候，注册自定义的Listener</span></span><br><span class="line"><span class="comment"> * 1. 在监听器中初始化线程池</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span> Amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Modifier</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span> 2019/7/14 16:41</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span> 1.0</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ServletListenerRegistrationConfig</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 注册自定义的Bean</span></span><br><span class="line"><span class="comment">     * 并且设置监听器，该监听器初始化线程池</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> ServletListenerRegistrationBean <span class="title">registrationBean</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ServletListenerRegistrationBean servletListenerRegistrationBean = <span class="keyword">new</span> ServletListenerRegistrationBean();</span><br><span class="line">        servletListenerRegistrationBean.setListener(<span class="keyword">new</span> InitThreadLocalPoolListen());</span><br><span class="line">        <span class="keyword">return</span> servletListenerRegistrationBean;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>按照标配，我们使用线程池来存储线程，当然使用线程池有很多的好处，主要如下：</li>
</ol>
<ul>
<li>降低资源消耗</li>
</ul>
<p>可以利用重复已创建的线程降低线程创建和销毁的消耗 </p>
<ul>
<li>提高响应速度</li>
</ul>
<p>当任务到达时，任务可以不需要等到线程创建就能立即执行</p>
<ul>
<li>提高线程的可管理性</li>
</ul>
<p>使用线程池可以进行统一分配、调优和监控</p>
<p>我们新建一个类主要是用来创建线程池，一般系统中线程池都是单例的，而且必须是线程安全的, 单例的线程安全有很多中，本博文这里使用静态内部类的方是来实现单例模式（任性，可以空间换时间）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span> com.amos.common.thread</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span> RequestThreadPool</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span> 请求线程池</span></span><br><span class="line"><span class="comment"> * 1. 使用线程池来管理线程，该线程池必须是单例的</span></span><br><span class="line"><span class="comment"> * 2. 线程池初始化成功后，创建缓存队列，并且和线程池进行绑定</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span> Amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Modifier</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span> 2019/7/14 16:47</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span> 1.0</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RequestThreadPool</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 核心线程数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;request.queue.corePoolSize:10&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> Integer corePoolSize;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 线程池最大线程数</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;request.queue.maximumPoolSize:20&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> Integer maximumPoolSize;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 线程最大存活时间</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;request.queue.keepAliveTime:60&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> Long keepAliveTime;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 初始化线程池 这里我们不使用Executors.newFixedThreadPool()方式，该种方式不推荐使用，</span></span><br><span class="line"><span class="comment">     * 主要是因为默认允许的队列的长度是Integer.MAX_VALUE,可能会造成OOM</span></span><br><span class="line"><span class="comment">     * 第一个参数：corePoolSize: 线程中核心线程数的最大值（能同时运行的最大的线程数）</span></span><br><span class="line"><span class="comment">     * 第二个参数：maximumPoolSize: 线程池中线程数的最大值</span></span><br><span class="line"><span class="comment">     * 第三个参数：keepAliveTime: 线程存活时间</span></span><br><span class="line"><span class="comment">     * 第四个参数：unit：时间单位</span></span><br><span class="line"><span class="comment">     * 第五个参数：BlockingQueue: 用于缓存任务的队列 这里使用 ArrayBlockingQueue 这个是有界队列</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> ExecutorService threadPool = <span class="keyword">new</span> ThreadPoolExecutor(<span class="keyword">this</span>.corePoolSize, <span class="keyword">this</span>.maximumPoolSize,</span><br><span class="line">            <span class="keyword">this</span>.keepAliveTime, TimeUnit.SECONDS,</span><br><span class="line">            <span class="keyword">new</span> ArrayBlockingQueue(<span class="keyword">this</span>.corePoolSize));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 构造器私有化，这样就不能通过new来创建实例对象</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;</span></span><br><span class="line"><span class="comment">     * 类实例化的时候 ，初始化队列的大小，并且绑定队列和线程池以及队列与线程的关系</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;</span></span><br><span class="line"><span class="comment">     * 初始化指定数量的队列</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">RequestThreadPool</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         *缓存队列集合来管理所有的缓存队列</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        RequestQueue requestQueue = RequestQueue.getInstance();</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="keyword">this</span>.corePoolSize; i++) &#123;</span><br><span class="line">            <span class="comment">/**</span></span><br><span class="line"><span class="comment">             * 缓存队列使用Request 接口来作为泛型，将可以将队列的类型添加定义，同时也可以通过多态的特性来实现子类的扩展</span></span><br><span class="line"><span class="comment">             * 目前Request只是定义，业务可以之后实现</span></span><br><span class="line"><span class="comment">             */</span></span><br><span class="line">            ArrayBlockingQueue&lt;Request&gt; queue = <span class="keyword">new</span> ArrayBlockingQueue&lt;&gt;(<span class="keyword">this</span>.corePoolSize);</span><br><span class="line">            requestQueue.add(queue);</span><br><span class="line">            <span class="comment">// 线程池和缓存队列通过线程来绑定</span></span><br><span class="line">            <span class="comment">// 每个线程对应一个队列</span></span><br><span class="line">            <span class="keyword">this</span>.threadPool.submit(<span class="keyword">new</span> RequestThread(queue));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 使用静态内部类来实现单例的模式（绝对的线程安全）</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 私有的静态变量，确保该变量不会被外部调用</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> RequestThreadPool requestThreadPool;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 静态代码块在类初始化时执行一次</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="keyword">static</span> &#123;</span><br><span class="line">            requestThreadPool = <span class="keyword">new</span> RequestThreadPool();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 静态内部类对外提供实例的获取方法</span></span><br><span class="line"><span class="comment">         *</span></span><br><span class="line"><span class="comment">         * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RequestThreadPool <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> requestThreadPool;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 请求线程池类对外提供获取实例的方法 由于外部类没有RequestThreadPool的实例对象，所以除了该方法，外部类无法创建额外的RequestThreadPool对象</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RequestThreadPool <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Singleton.getInstance();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我将整个代码贴出来，方便大家查看，该类的主要用途是系统启动的时候初始化线程池，并且创建缓存队列，将队列和线程池进行绑定</p>
<p>该类中的构造器是<code>private</code>修饰的，这样处理的目的主要是为了不让线程池创建之后再创建多余的实例对象，其次也是为了方便在构造器中完成线程池与缓存队列之间的绑定</p>
<p>既然构造器被私有化了，我们就得提供一个供外部获取实例的方法，这里我们使用了静态内部类是实现单例模式，让线程池的实例保持一个。为什么要使用静态内部了呢？</p>
<ul>
<li>外部内加载的时候，不需要立即加载内部类，内部类不被加载，就不会初始化，故而不占用内存</li>
<li>当getInstance被调用时，才会去初始化实例，第一次调用getInstance会导致虚拟机加载实例，这种方法不仅能确保线程的安全，也能保证单例的唯一性</li>
</ul>
<p>线程池存储的线程主要是用来处理外部过来的请求，所以缓存对列主要用来对请求进行处理，而且请求队列必须也是单例的</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: rabbitmq</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: RequestQueue</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.common.request</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: zhuqb</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: 请求的队列</span></span><br><span class="line"><span class="comment"> * &lt;p/&gt;</span></span><br><span class="line"><span class="comment"> * 1. 这里需要使用单例模式来确保请求的队列的对象只有一个</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/7/15 0015 下午 14:18</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RequestQueue</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 构造器私有化，这样就不能通过new来创建实例对象</span></span><br><span class="line"><span class="comment">     * 这里构造器私有化 这点跟枚举一样的，所以我们也可以通过枚举来实现单例模式，详见以后的博文</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">RequestQueue</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 内存队列</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> List&lt;ArrayBlockingQueue&lt;Request&gt;&gt; queues = <span class="keyword">new</span> ArrayList&lt;ArrayBlockingQueue&lt;Request&gt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 私有的静态内部类来实现单例</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">Singleton</span> </span>&#123;</span><br><span class="line">        <span class="keyword">private</span> <span class="keyword">static</span> RequestQueue queue;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">static</span> &#123;</span><br><span class="line">            queue = <span class="keyword">new</span> RequestQueue();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> RequestQueue <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> queue;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取 RequestQueue 对象</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> RequestQueue <span class="title">getInstance</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Singleton.getInstance();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 向容器中添加队列</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> queue</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(ArrayBlockingQueue&lt;Request&gt; queue)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.queues.add(queue);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>线程池和缓存队列通过线程来绑定，一个线程对应一个缓存队列，在线程里来处理缓存队列中的逻辑</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: rabbitmq</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: RequestThread</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.common.thread</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: zhuqb</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: 执行请求的工作线程</span></span><br><span class="line"><span class="comment"> * &lt;p/&gt;</span></span><br><span class="line"><span class="comment"> * 线程和队列进行绑定，然后再线程中处理对应的业务逻辑</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/7/15 0015 下午 14:34</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RequestThread</span> <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">Boolean</span>&gt; </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 队列</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> ArrayBlockingQueue&lt;Request&gt; queue;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">RequestThread</span><span class="params">(ArrayBlockingQueue&lt;Request&gt; queue)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.queue = queue;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 方法中执行具体的业务逻辑</span></span><br><span class="line"><span class="comment">     * TODO 这里我们先搭建整理的框架，后面在慢慢处理缓存队列</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Boolean <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>然后再监听器中获取线程时的实例对象来完成线程池的启动初始化<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span> com.amos.common.listener</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span> InitThreadLocalPoolListen</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span> 系统初始化监听器 初始队列</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span> Amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Modifier</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span> 2019/7/14 16:44</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span> 1.0</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InitThreadLocalPoolListen</span> <span class="keyword">implements</span> <span class="title">ServletContextListener</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 系统初始化队列</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> sce</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">contextInitialized</span><span class="params">(ServletContextEvent sce)</span> </span>&#123;</span><br><span class="line">        RequestThreadPool.getInstance();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 监听器销毁执行的逻辑</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> sce</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">contextDestroyed</span><span class="params">(ServletContextEvent sce)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>至此，我们框架的代码算是搭建完成了，下面我们以商品购买库存减一的功能来实现缓存与数据库双写一致性性解决方案的代码实现</p>
<p><strong>代码逻辑如下</strong>：</p>
<blockquote>
<ol>
<li>需要集成redis和mysql数据库操作</li>
<li>需要一个处理redis的请求和处理数据库的请求业务逻辑代码</li>
<li>在缓存队列的线程中执行基于缓存和数据库双写一致性的代码</li>
</ol>
</blockquote>
<p>接下来我们开始搭建环境，关于Redis的环境搭建可以参考我以前的博文<a href="https://www.jianshu.com/p/a0bd76adcc1d" target="_blank" rel="noopener">《Redis教程（一）——Redis安装》</a>，然后我们在SpringBoot中来集成操作Redis的功能，</p>
<ul>
<li>集成Redis和mysql的数据库操作</li>
</ul>
<p>在pom文件中添加springBoot整合redis的依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 添加SpringBoot集成Redis的依赖--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1.6.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>然后编写Redis的操作功能类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span> com.amos.common.util</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span> RedisUtils</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span> redis的操作类</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span> Amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Modifier</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span> 2019/8/18 0:13</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span> 1.0</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RedisUtils</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Log logger = LogFactory.getLog(<span class="keyword">this</span>.getClass());</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RedisTemplate&lt;String, Object&gt; redisTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 指定键缓存实效的时间</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key        指定的键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> expireTime 超时时间 毫秒</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">expire</span><span class="params">(String key, <span class="keyword">long</span> expireTime)</span> </span>&#123;</span><br><span class="line">        AmExcepitonEnum.NOT_NULL.assertNotEmpty(key, <span class="string">"指定的键不能为空"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (expireTime &lt; <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RabbitMQException(<span class="string">"超时时间不能小于0"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.redisTemplate.expire(key, expireTime, TimeUnit.MICROSECONDS);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> Boolean.FALSE;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 判断是否有指定的key</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key 指定的键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasKey</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        AmExcepitonEnum.NOT_NULL.assertNotEmpty(key, <span class="string">"指定的键不能为空"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.redisTemplate.hasKey(key);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> Boolean.FALSE;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 保存键值</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key   保存的键</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> value 保存的值</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">save</span><span class="params">(String key, Object value)</span> </span>&#123;</span><br><span class="line">        AmExcepitonEnum.NOT_NULL.assertNotEmpty(key, <span class="string">"指定的键不能为空"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.redisTemplate.opsForValue().set(key, value);</span><br><span class="line">            <span class="keyword">return</span> Boolean.TRUE;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> Boolean.FALSE;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除key</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">del</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        AmExcepitonEnum.NOT_NULL.assertNotEmpty(key, <span class="string">"指定的键不能为空"</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">this</span>.redisTemplate.delete(key);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> Boolean.FALSE;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 保存有实效时间的键值对</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> value</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> expireTime 实效时间 单位毫秒</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">save</span><span class="params">(String key, Object value, <span class="keyword">long</span> expireTime)</span> </span>&#123;</span><br><span class="line">        AmExcepitonEnum.NOT_NULL.assertNotEmpty(key, <span class="string">"键值不能为空"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.redisTemplate.opsForValue().set(key, value, expireTime, TimeUnit.MICROSECONDS);</span><br><span class="line">            <span class="keyword">return</span> Boolean.TRUE;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> Boolean.FALSE;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>至此，我们的集成Redis就已经完成了，可以自己写个测试类测试下</p>
<p>我们再来整合mybatis</p>
<p>我们在pom文件中添加mybatis的依赖<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 集成Mybatis --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>mysql<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mysql-connector-java<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">scope</span>&gt;</span>runtime<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.mybatis.spring.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mybatis-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>接着在创建创建如下的目录结构：<br><img src="https://s2.ax1x.com/2019/08/18/mlkQi9.png" alt="image"></p>
<p>在application.yml文件中添加<br><figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line"><span class="attr">  datasource:</span></span><br><span class="line"><span class="attr">    driver-class-name:</span> <span class="string">com.mysql.jdbc.Driver</span></span><br><span class="line"><span class="attr">    username:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">    password:</span> <span class="number">123</span></span><br><span class="line"><span class="attr">    url:</span> <span class="attr">jdbc:mysql://localhost:3306/amos?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false</span></span><br><span class="line"><span class="attr">mybatis:</span></span><br><span class="line"><span class="attr">  config-location:</span> <span class="attr">classpath:/mybatis/config/mybatis-config.xml</span></span><br><span class="line"><span class="attr">  mapper-locations:</span> <span class="attr">classpath:/mybatis/mapper/*.xml</span></span><br></pre></td></tr></table></figure></p>
<p>在 classpath:/mybatis/config/mybatis-config.xml中添加<br><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE configuration</span></span><br><span class="line"><span class="meta">        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"</span></span><br><span class="line"><span class="meta">        "http://mybatis.org/dtd/mybatis-3-config.dtd"&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">configuration</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">settings</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">setting</span> <span class="attr">name</span>=<span class="string">"mapUnderscoreToCamelCase"</span> <span class="attr">value</span>=<span class="string">"true"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">settings</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">typeAliases</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">package</span> <span class="attr">name</span>=<span class="string">"com.amos.doublewriterconsistence.entity"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">typeAliases</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">configuration</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>其余的配置主要是常见的mybatis的Mapper和Entity,这里我就不详细列举出来了，可以参考我的Gitee的源码,我里面添加了详细的注释，方便阅读<br><a href="https://gitee.com/amos_zhu/doubleWriterConsistence" target="_blank" rel="noopener">doubleWriterConsistence</a></p>
<p>至此SpringBoot集成Mybatis的框架也完成了，大家可以自己编写测试类进行测试功能是否正常，同时我们也完成了代码逻辑中的第一点，接下来是我们此次代码的重点，着重讲解下，如果使用缓存队列来实现一致性的功能代码</p>
<ul>
<li>新增业务处理缓存和数据库的业务逻辑代码</li>
</ul>
<p>这里我们先将设计业务逻辑的代码编写出来</p>
<ol>
<li>库存的操作方法</li>
</ol>
<p>统一提供库存的方法: 从数据库中查询，更新数据库，从缓存中查询，删除缓存数据，保存缓存数据<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: double-writer-consistence</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: InventoryServiceImpl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.doublewriterconsistence.service</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>:</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/8/19 0019 下午 14:23</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InventoryServiceImpl</span> <span class="keyword">implements</span> <span class="title">InventoryService</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    InventoryMapper inventoryMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    RedisUtils redisUtils;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除库存的缓存</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Boolean <span class="title">removeInventoryCache</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"移除库存：&#123;&#125; 的缓存"</span>, key);</span><br><span class="line">        key = InventoryKeyUtils.getInventoryKey(key);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.redisUtils.del(key);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新数据库库存记录</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> inventory</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateInventory</span><span class="params">(Inventory inventory)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"更新库存：&#123;&#125; 的库存记录"</span>, inventory.getId());</span><br><span class="line">        <span class="keyword">this</span>.inventoryMapper.update(inventory);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 保存库存的缓存记录</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> inventory</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Boolean <span class="title">saveInventoryCache</span><span class="params">(Inventory inventory)</span> </span>&#123;</span><br><span class="line">        AmExcepitonEnum.NOT_NULL.assertNotEmpty(inventory);</span><br><span class="line">        String key = InventoryKeyUtils.getInventoryKey(inventory.getId());</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"保存缓存数据的Key：&#123;&#125;"</span>, key);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.redisUtils.save(key, inventory);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取指定key的缓存值</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Inventory <span class="title">getInventoryCache</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        key = InventoryKeyUtils.getInventoryKey(key);</span><br><span class="line">        Object object = <span class="keyword">this</span>.redisUtils.get(key);</span><br><span class="line">        <span class="keyword">return</span> JSONObject.parseObject(JSONObject.toJSONString(object), Inventory.class);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据id查询库存记录</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Inventory <span class="title">selectById</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.inventoryMapper.selectById(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 设置空值在缓存中的失效时间</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> inventoryKey 键值</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> expireTime   失效时间</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">saveNullForCache</span><span class="params">(String inventoryKey, <span class="keyword">long</span> expireTime)</span> </span>&#123;</span><br><span class="line">        AmExcepitonEnum.NOT_NULL.assertNotEmpty(inventoryKey);</span><br><span class="line">        String key = InventoryKeyUtils.getInventoryKey(inventoryKey);</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"保存空值，Key：&#123;&#125;"</span>, key);</span><br><span class="line">        <span class="keyword">this</span>.redisUtils.save(key, <span class="string">""</span>, expireTime);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol start="2">
<li>读取数据的代码逻辑 </li>
</ol>
<p>一个读请求过来，我们需要从数据库中读取对应的缓存记录，并且将该数据保存到缓存中，由于我们需要将所有的请求都是通过缓存队列来处理的，所以缓存的操作类应该实现Request接口，在定义好的方法中实现缓存读取的操作</p>
<p>我们在缓存读取的操作类中添加了<code>isForceFresh</code>字段来为过滤多重读请求提供支持<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: rabbitmq</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: InventoryCacheRequestImpl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.common.request.impl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: 处理缓存的业务请求</span></span><br><span class="line"><span class="comment"> * 缓存这边我们需要在数据库中查询出对应的数据，然后将数据写入到缓存中</span></span><br><span class="line"><span class="comment"> * 由此我们需要获取库存的id，根据id获取库存的数据</span></span><br><span class="line"><span class="comment"> * 然后将库存数据写入到缓存中 数据中的key是库存ID的标识，value是查询出来的缓存数据</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/8/19 0019 上午 8:59</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InventoryCacheRequest</span> <span class="keyword">implements</span> <span class="title">Request</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 库存的id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> String inventoryId;</span><br><span class="line">    <span class="keyword">private</span> InventoryService inventoryService;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 是否需要更新缓存</span></span><br><span class="line"><span class="comment">     * 数据更新该值是false</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> Boolean isForceFresh;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">InventoryCacheRequest</span><span class="params">(String inventoryId, InventoryService inventoryService, Boolean isForceFresh)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.inventoryId = inventoryId;</span><br><span class="line">        <span class="keyword">this</span>.inventoryService = inventoryService;</span><br><span class="line">        <span class="keyword">this</span>.isForceFresh = isForceFresh;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 1. 根据id到数据库中查询对应的库存数据</span></span><br><span class="line"><span class="comment">     * 2. 查询到了则将数据保存到缓存中</span></span><br><span class="line"><span class="comment">     * 3. 如果查询不到的话则将对应的空数据保存到缓存中，并且设置失效时间</span></span><br><span class="line"><span class="comment">     * 这里的查询不到数据也保存到缓存中，主要是为了防止恶意请求，以防通过不断的循环一个查找不到记录的id来不断的请求数据库，给数据库造成了访问压力，占用系统的资源</span></span><br><span class="line"><span class="comment">     * 同时，也给缓存数据设置失效时间，方便数据发生变化时，及时提供变更后的数据</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 首先从数据库中查询对应的库存数据</span></span><br><span class="line">        Inventory inventory = <span class="keyword">this</span>.inventoryService.selectById(<span class="keyword">this</span>.inventoryId);</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"库存缓存操作——查询数据库数据:"</span> + JSONObject.toJSONString(inventory));</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isEmpty(inventory)) &#123;</span><br><span class="line">            <span class="comment">// 查询不到数据的话，对应的key存储空字符串，并且设置失效时间</span></span><br><span class="line">            <span class="keyword">this</span>.inventoryService.saveNullForCache(InventoryKeyUtils.getInventoryKey(<span class="keyword">this</span>.inventoryId), <span class="number">1000</span>);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.logger.info(<span class="string">"库存缓存操作——保存缓存数据:"</span> + JSONObject.toJSONString(inventory));</span><br><span class="line">            <span class="keyword">this</span>.inventoryService.saveInventoryCache(inventory);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getInventoryId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.inventoryId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Boolean <span class="title">isForceRefresh</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.isForceFresh;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ol start="3">
<li>更新数据的代码逻辑</li>
</ol>
<p>提高数据更新的请求操作,数据更新过程中，我们需要先删除缓存中的数据，然后再更新数据库中的数据<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span> com.amos.consumer.service.impl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span> InventoryServiceImpl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span> 数据更新操作</span></span><br><span class="line"><span class="comment"> * 1. 先删除缓存中的数据</span></span><br><span class="line"><span class="comment"> * 2. 再更新数据库中的数据</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Author</span> Amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Modifier</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Date</span> 2019/8/18 22:16</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span> 1.0</span></span><br><span class="line"><span class="comment"> **/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InventoryDBRequest</span> <span class="keyword">implements</span> <span class="title">Request</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line">    <span class="keyword">private</span> Inventory inventory;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> InventoryService inventoryService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 构造器</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> inventory</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> inventoryService</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">InventoryDBRequest</span><span class="params">(Inventory inventory, InventoryService inventoryService)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.inventory = inventory;</span><br><span class="line">        <span class="keyword">this</span>.inventoryService = inventoryService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 库存数据库操作</span></span><br><span class="line"><span class="comment">     * 1. 先删除缓存中对应的数据</span></span><br><span class="line"><span class="comment">     * 2. 更新数据库中的数据</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">process</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"数据库操作——移除缓存中的数据"</span>);</span><br><span class="line">        <span class="comment">// 首先删除缓存中的数据</span></span><br><span class="line">        <span class="keyword">this</span>.inventoryService.removeInventoryCache(<span class="keyword">this</span>.inventory.getId());</span><br><span class="line">        <span class="comment">// 为了测试 所以这里操作时间长点</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">this</span>.logger.info(<span class="string">"数据库操作——等待3秒操作"</span>);</span><br><span class="line">            Thread.sleep(<span class="number">3000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 再更新数据库中的数据</span></span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"数据库操作——更新数据库中的数据"</span>);</span><br><span class="line">        <span class="keyword">this</span>.inventoryService.updateInventory(<span class="keyword">this</span>.inventory);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 接口返回库存记录的ID</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getInventoryId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.inventory.getId();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 始终不更新</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Boolean <span class="title">isForceRefresh</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Boolean.FALSE;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>在队列中整合缓存和数据库的业务逻辑处理</li>
</ul>
<p>上面我们已经完成了读数据和数据更新的功能，现在我们需要在后台的队列处理中，进行相关的业务处理，业务的处理我们已经定义了process公用方法了，现在主要的逻辑是在数据更新过程中如何过滤多次的读请求</p>
<p>还记得我们上面的<code>isForceFresh</code>字段么，这里我们主要是根据这个字段来判断是否是重复的读请求，下面是代码，代码中有详细的注释说明，方便阅读<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 方法中执行具体的业务逻辑</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Boolean <span class="title">call</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="comment">// ArrayBlockingQueue take方法 获取队列排在首位的对象，如果队列为空或者队列满了，则会被阻塞住</span></span><br><span class="line">            Request request = <span class="keyword">this</span>.queue.take();</span><br><span class="line">            Boolean forceFresh = request.isForceRefresh();</span><br><span class="line">            <span class="comment">// 如果需要更新的话</span></span><br><span class="line">            <span class="keyword">if</span> (!forceFresh) &#123;</span><br><span class="line">                RequestQueue requestQueue = RequestQueue.getInstance();</span><br><span class="line">                Map&lt;String, Boolean&gt; tagMap = requestQueue.getTagMap();</span><br><span class="line">                <span class="comment">// 如果是请求缓存中的数据</span></span><br><span class="line">                <span class="keyword">if</span> (request <span class="keyword">instanceof</span> InventoryCacheRequest) &#123;</span><br><span class="line">                    Boolean tag = tagMap.get(request.getInventoryId());</span><br><span class="line">                    <span class="comment">// 如果tag为空 则说明读取缓存的操作</span></span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">null</span> == tag) &#123;</span><br><span class="line">                        tagMap.put(request.getInventoryId(), Boolean.FALSE);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="comment">// tag为不为空，并且为true时，说明上一个请求是更新数据库的</span></span><br><span class="line">                    <span class="comment">// 那么此时我们需要将标志位修改为False</span></span><br><span class="line">                    <span class="keyword">if</span> (tag != <span class="keyword">null</span> &amp;&amp; tag) &#123;</span><br><span class="line">                        tagMap.put(request.getInventoryId(), Boolean.FALSE);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="comment">// tag不为空，并且为false时，说明前面已经有数据库+缓存的请求了，</span></span><br><span class="line">                    <span class="comment">// 那么这个请求应该是读请求，可以直接过滤掉了，不要添加到队列中</span></span><br><span class="line">                    <span class="keyword">if</span> (tag != <span class="keyword">null</span> &amp;&amp; !tag) &#123;</span><br><span class="line">                        <span class="keyword">return</span> Boolean.TRUE;</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (request <span class="keyword">instanceof</span> InventoryDBRequest) &#123;</span><br><span class="line">                    <span class="comment">// 如果是更新数据库的操作</span></span><br><span class="line">                    tagMap.put(request.getInventoryId(), Boolean.TRUE);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 执行请求处理</span></span><br><span class="line">            <span class="keyword">this</span>.logger.info(<span class="string">"缓存队列执行+++++++++++++++++，&#123;&#125;"</span>, request.getInventoryId());</span><br><span class="line">            request.process();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> Boolean.TRUE;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>至此,处理业务逻辑的代码我们已经完成了，这里需要注意一点，所有的请求我们都需要打入到缓存队列中来执行下，所以同一库存，我们需要他打入到同一缓存队列中进行处理，如何来实现这个这功能呢？ 这里我们使用hash值取模的方式来实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: double-writer-consistence</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: RequestAsyncProcessServiceImpl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.doublewriterconsistence.service.impl</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>:</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/8/19 0019 下午 15:23</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RequestAsyncProcessServiceImpl</span> <span class="keyword">implements</span> <span class="title">RequestAsyncProcessService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 路由到指定的缓存队列中</span></span><br><span class="line"><span class="comment">     * doubleWriterConsistence</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> request</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">route</span><span class="params">(Request request)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">// 做请求的路由，根据每个请求的商品id，路由到对应的内存队列中去</span></span><br><span class="line">            ArrayBlockingQueue&lt;Request&gt; queue = <span class="keyword">this</span>.getRoutingQueue(request.getInventoryId());</span><br><span class="line">            <span class="comment">// 将请求放入对应的队列中，完成路由操作</span></span><br><span class="line">            queue.put(request);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 根据库存记录路由到指定的缓存队列</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> key</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> ArrayBlockingQueue&lt;Request&gt; <span class="title">getRoutingQueue</span><span class="params">(String key)</span> </span>&#123;</span><br><span class="line">        RequestQueue requestQueue = RequestQueue.getInstance();</span><br><span class="line">        <span class="keyword">int</span> h;</span><br><span class="line">        <span class="keyword">int</span> hash = (key == <span class="keyword">null</span>) ? <span class="number">0</span> : (h = key.hashCode()) ^ (h &gt;&gt; <span class="number">16</span>);</span><br><span class="line">        <span class="comment">// 对hash值取模，将hash值路由到指定的内存队列中，比如内存队列大小8</span></span><br><span class="line">        <span class="comment">// 用内存队列的数量对hash值取模之后，结果一定是在0~7之间</span></span><br><span class="line">        <span class="comment">// 所以任何一个商品id都会被固定路由到同样的一个内存队列中去的</span></span><br><span class="line">        <span class="keyword">int</span> index = (requestQueue.size() - <span class="number">1</span>) &amp; hash;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"路由的缓存队列为：&#123;&#125;"</span>, index);</span><br><span class="line">        <span class="keyword">return</span> requestQueue.getQueue(index);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>到这里，我们就已经完成了相关代码的开发，接下来需要我们进行编写测试代码来测试下功能是否正常</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Copyright © 2018 五月工作室. All rights reserved.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Project</span>: double-writer-consistence</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@ClassName</span>: InventoryController</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Package</span>: com.amos.doublewriterconsistence.web</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>: amos</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Description</span>: 主要测试</span></span><br><span class="line"><span class="comment"> * 1. 所有的请求是否从缓存队列中走</span></span><br><span class="line"><span class="comment"> * 2. 通过延迟数据的操作，看看读请求是否有等待</span></span><br><span class="line"><span class="comment"> * 3，读请求通过之后，相同的读请求是否直接返回</span></span><br><span class="line"><span class="comment"> * 4. 读请求的数据是否从缓存中获取</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>: 2019/8/19 0019 下午 15:31</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@Version</span>: V1.0</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping</span>(value = <span class="string">"/inventory"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">InventoryController</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(<span class="keyword">this</span>.getClass());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    InventoryService inventoryService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    RequestAsyncProcessService requestAsyncProcessService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新库存的数据记录</span></span><br><span class="line"><span class="comment">     * 1. 将更新数据的记录路由到指定的队列中</span></span><br><span class="line"><span class="comment">     * 2. 后台不断的将从队列中取值去处理</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> inventory</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@PostMapping</span>(value = <span class="string">"/updateInventory"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result <span class="title">updateInventory</span><span class="params">(@RequestBody Inventory inventory)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Request request = <span class="keyword">new</span> InventoryDBRequest(inventory, <span class="keyword">this</span>.inventoryService);</span><br><span class="line">            <span class="keyword">this</span>.requestAsyncProcessService.route(request);</span><br><span class="line">            <span class="keyword">return</span> ResultWapper.success();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.logger.error(e.getMessage());</span><br><span class="line">            <span class="keyword">return</span> ResultWapper.error(e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 获取库存记录</span></span><br><span class="line"><span class="comment">     * 如果在在一定时间内获取不到数据，则直接从数据库中获取，并且数据写入到缓存中</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@GetMapping</span>(value = <span class="string">"/getInventory/&#123;id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result <span class="title">getInventory</span><span class="params">(@PathVariable(<span class="string">"id"</span>)</span> String id) </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.logger.info(<span class="string">"获取库存记录：&#123;&#125;"</span>, id);</span><br><span class="line">        Inventory inventory = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Request request = <span class="keyword">new</span> InventoryCacheRequest(id, <span class="keyword">this</span>.inventoryService, Boolean.FALSE);</span><br><span class="line">            <span class="keyword">this</span>.requestAsyncProcessService.route(request);</span><br><span class="line">            <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line">            <span class="keyword">long</span> waitTime = <span class="number">0L</span>;</span><br><span class="line">            <span class="comment">// 不断循环从缓存中获取数据</span></span><br><span class="line">            <span class="comment">// 如果在在一定时间内获取不到数据，则直接从数据库中获取，并且数据写入到缓存中</span></span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (waitTime &gt; <span class="number">3000</span>) &#123;</span><br><span class="line">                    <span class="keyword">break</span>;</span><br><span class="line">                &#125;</span><br><span class="line">                inventory = <span class="keyword">this</span>.inventoryService.getInventoryCache(id);</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">null</span> != inventory) &#123;</span><br><span class="line">                    <span class="keyword">this</span>.logger.info(<span class="string">"从缓存中获取到数据"</span>);</span><br><span class="line">                    <span class="keyword">return</span> ResultWapper.success(inventory);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    Thread.sleep(<span class="number">20</span>);</span><br><span class="line">                    waitTime = System.currentTimeMillis() - startTime;</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// 直接从数据库中获取数据</span></span><br><span class="line">            inventory = <span class="keyword">this</span>.inventoryService.selectById(id);</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> != inventory) &#123;</span><br><span class="line">                request = <span class="keyword">new</span> InventoryCacheRequest(id, <span class="keyword">this</span>.inventoryService, Boolean.TRUE);</span><br><span class="line">                <span class="keyword">this</span>.requestAsyncProcessService.route(request);</span><br><span class="line">                <span class="keyword">return</span> ResultWapper.success(inventory);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> ResultWapper.error(<span class="string">"查询不到数据"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">this</span>.logger.error(e.getMessage());</span><br><span class="line">            <span class="keyword">return</span> ResultWapper.error(e.getMessage());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面详细的代码可以参考我的Gitee——<a href="https://gitee.com/amos_zhu/doubleWriterConsistence" target="_blank" rel="noopener">doubleWriterConsistence</a></p>
  </article>
  <aside class="table-content" id="site-toc">
  <div class="table-content-title">
    <i class="fa fa-arrow-right fa-lg" id="site-toc-hide-btn"></i>
    <span>目录</span>
  </div>
  <div class="table-content-main">
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#谈谈缓存与数据库数据一致性的问题"><span class="toc-text">谈谈缓存与数据库数据一致性的问题</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#注意点"><span class="toc-text">注意点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#代码实现"><span class="toc-text">代码实现</span></a></li></ol>
  </div>
</aside>
  
    <aside class="passage-copyright">
      <div>本文作者: Amos Zhu</div>
      
        <div>
          原文链接: 
          <a href target="_blank">http://amos_zhu.gitee.io/passages/缓存与数据库双写一致性的解决方案——附上代码解决方案/</a>
        </div>
      
      <div>
        版权声明: 本博客所有文章除特别声明外, 均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议. 转载请注明出处!
      </div>
    </aside>
  
  
    <div class="passage-tags">
     
      <a href="/blog/tags/redis/"><i class="fa fa-tags"></i>redis</a>
     
      <a href="/blog/tags/stuff/"><i class="fa fa-tags"></i>stuff</a>
     
      <a href="/blog/tags/Spring-Boot/"><i class="fa fa-tags"></i>Spring Boot</a>
    
    </div>
  
</div>

    </main>
    
      
<div class="site-comment-contanier" data-plateform="leancloud">
  
    <p id="site-comment-info">
      <i class="fa fa-spinner fa-spin"></i> 评论加载中
    </p>
    <div id="site-comment"></div>
  
</div>
    
    <div class="site-footer-wrapper">
  <footer class="site-footer">
    
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">博客推荐</h5>
          
            <span class="site-footer-item">
              <a href="http://youzhixueyuan.com/series/java" target="_blank">优知学院</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://ruanyifeng.com/" target="_blank">阮一峰的个人网站</a>
            </span>
          
        </div>
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">系列教程</h5>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/redis" target="_blank">Redis系列教程</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/rabbitMQ/" target="_blank">RabbitMQ教程</a>
            </span>
          
            <span class="site-footer-item">
              <a href="http://amos_zhu.gitee.io/blog/kafka/" target="_blank">Kafka架构探险</a>
            </span>
          
        </div>
      
        <div class="site-footer-col">
          <h5 class="site-footer-title">抓到我</h5>
          
            <span class="site-footer-item">
              <a href="https://gitee.com/amos_zhu" target="_blank">Gitee</a>
            </span>
          
            <span class="site-footer-item">
              <a href="https://blog.csdn.net/wdcl2468" target="_blank">CSDN</a>
            </span>
          
            <span class="site-footer-item">
              <a href="https://www.jianshu.com/u/2dbe61b1f3c3" target="_blank">简书</a>
            </span>
          
        </div>
      
    
    <div class="site-footer-info">
      <i class="fa fa-clock-o"></i> 本站已稳定运行<span id="site-time"></span>
    </div>
    
      <div class="site-footer-info">
        <i class="fa fa-paw"></i> 您是本站第 <span id="site-count"></span> 位访客
      </div>
    
    
      <div class="site-footer-info">
        <i class="fa fa-at"></i> Email: amoszhu@aliyun.com
      </div>
    
    <div class="site-footer-info">
      <i class="fa fa-copyright"></i> 
      2019 <a href="https://github.com/dongyuanxin/theme-ad/" target="_blank">Theme-AD</a>.
      Created by <a href="https://godbmw.com/" target="_blank">GodBMW</a>.
      All rights reserved.
    </div>
  </footer>
</div>
    <div id="site-layer" style="display:none;">
  <div class="site-layer-content">
    <div class="site-layer-header">
      <span class="site-layer-header-title" id="site-layer-title"></span>
      <i class="fa fa-close" id="site-layer-close"></i>
    </div>
    <div class="site-layer-body" id="site-layer-container">
      <div class="site-layer-input" id="site-layer-search" style="display: none;">
        <div class="site-layer-input-choose">
          <a href="javascript:void(0);" title="Change Search Engine">Google</a>
        </div>
        <input type="text">
        <i class="fa fa-search"></i>
      </div>
      
        <div class="site-layer-reward" id="site-layer-reward" style="display: none;">
          
            <div>
              <img src="/blog/images/wechat.png" alt="WeChat">
              
                <p>WeChat</p>
              
            </div>
          
            <div>
              <img src="/blog/images/alipay.png" alt="AliPay">
              
                <p>AliPay</p>
              
            </div>
          
        </div>
      
      <div id="site-layer-welcome" style="display:none;"></div>
    </div>
  </div>
</div>
    

<div class="bottom-bar">
  <div class="bottom-bar-left">
    <a href="/blog/passages/SpringBoot-Redis-MemCache-Nginx-Lua实现三级缓存架构（二）——Nginx环境安装和整合Lua/" data-enable="true">
      <i class="fa fa-arrow-left"></i>
    </a>
    <a href="/blog/passages/Centos7上安装Elasticsearch7-3-0/" data-enable="true">
      <i class="fa fa-arrow-right"></i>
    </a>
  </div>
  <div class="bottom-bar-right">
    <a href="javascript:void(0);" data-enable="true" id="site-toc-show-btn">
      <i class="fa fa-bars"></i>
    </a>
    
      <a href="#site-comment" data-enable="true">
        <i class="fa fa-commenting"></i>
      </a>
    
    <a href="javascript:void(0);" id="site-toggle-share-btn">
      <i class="fa fa-share-alt"></i>
    </a>
    
      <a href="javascript:void(0);" id="site-reward">
        <i class="fa fa-thumbs-up"></i>
      </a>
    
    <a href="javascript:void(0);" id="back-top-btn">
      <i class="fa fa-chevron-up"></i>
    </a>
  </div>
</div>
    <div id="share-btn">
  
  
  
  
    <a id="share-btn-qq" href="javascript:void(0);" target="_blank">
      <i class="fa fa-qq"></i>
    </a>
  
  
    <a id="share-btn-wechat" href="javascript:void(0);" target="_blank">
      <i class="fa fa-wechat"></i>
    </a>
  
</div>
    


  <script async>
  (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      }
      else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>



  <script async>
    (function(){
    var src = (document.location.protocol == "http:") ? "http://js.passport.qihucdn.com/11.0.1.js?":"https://jspassport.ssl.qhimg.com/11.0.1.js?";
    document.write('<script src="' + src + '" id="sozz"><\/script>');
    })();
  </script>


    
  </body>
</html>